import React from 'react';
import { inject, observer } from 'mobx-react';
import { observable, action, toJS } from 'mobx';
import { WeaEchart } from 'ecCom';
import { isEqual, isEmpty } from 'lodash';
import { WeaDialog, WeaLocaleProvider } from 'ecCom';
import * as ReportUtil from '../../util/report';

const getLabel = WeaLocaleProvider.getLabel;

@inject('smsReportStore')
@observer
class SmsReportEcharts extends React.Component {
  constructor(props) {
    super(props);
    const xData = this.props.reportData.xAxis && this.props.reportData.xAxis.data || [];
    const yData = this.props.reportData.yAxis && this.props.reportData.yAxis.data || [];
    // const yData = [14836, 9000, 8000, 10000, 5464];
    // const xData = ['2018-01','2018-02','2018-03','2018-04'];
    this.state = {
      condition: { // 默认搜索条件

      },
      option: {
        xAxis: {
          data: xData || [],
          axisLine: { lineStyle: { color: '#B2B2B2' } },
          splitLine: {
            show: false,
          },
          axisTick: {
            lineStyle: { color: '#B2B2B2' },
            alignWithLabel: false,
          },
          boundaryGap: true,
          axisLabel: {
            interval: 0,
            textStyle: {
              color: '#333333',
            },
          },
        },
        yAxis: {
          axisLine: { show: false, lineStyle: { color: '#B2B2B2' } },
          axisLabel: {
            index: 0,
            textStyle: {
              color: '#333333',
            },
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            show: true,
          },
          minInterval: 1,
        },
        grid: {
          left: 50,
          right: 0,
          borderColor: '#c5c5c5',
        },
        series: [
          {
            name: `${getLabel(18953, '短信数量')}: 46500`,
            type: 'bar',
            data: yData || [],
            barWidth: '50%',
            itemStyle: {
              normal: {
                color: (params) => {
                  if (params.name.length == 7) {
                    return WeaEchart.colors[params.dataIndex % 10];
                  }
                    return WeaEchart.colors[0];
                },
              },
            },
          },
        ],
        tooltip: {
          trigger: 'item',
          formatter: (params, ticket, callback) => {
            let str = `${params.name} : ${params.value}`;
            if (params.name.length == 7) {
              str = `${params.name} : ${params.value}<br/> ${getLabel(82279, '点击查看')} ${params.name} ${getLabel(22045, '详情')} `;
            }
            return str;
          },
        },
        toolbox: {
          show: false,
          right: '25px',
          feature: {
            saveAsImage: { show: true },
          },
        },
      },
    };
  }

  componentDidMount() {

  }

  componentWillReceiveProps(nextProps) {
    let { option, option: { series, xAxis } } = this.state;
    const xAxisState = option.xAxis;
    const yAxisState = option.yAxis;

    const { reportData: { title = '' } } = this.props;
    const xData = this.props.reportData.xAxis && this.props.reportData.xAxis.data ? this.props.reportData.xAxis.data : [];
    const yData = this.props.reportData.yAxis && this.props.reportData.yAxis.data ? this.props.reportData.yAxis.data : [];
    const xDataNext = nextProps.reportData.xAxis && nextProps.reportData.xAxis.data || [];
    const yDataNext = nextProps.reportData.yAxis && nextProps.reportData.yAxis.data || [];
    const titleNext = nextProps.reportData.title && nextProps.reportData.title.text || '';

    let nState = null;
    title !== titleNext && (series[0].name = titleNext) && (nState = { option: { ...option, series } });
    !isEqual(xData, xDataNext) && (xAxis.data = xDataNext) && (nState = { option: { ...option, xAxis: { ...xAxisState, data: xDataNext } } });
    !isEqual(yData, yDataNext) && (series[0].data = yDataNext) && (nState = { option: { ...option, series } });
    nState && this.setState(nState, () => {
      this.refs.chart && this.refs.chart.paint();
    });
  }

  chartAction = (chart) => {
    const { year, setState, getReportData } = this.props.smsReportStore;
    chart.off('click');
    chart.on('click', (params) => {
      // 月份可点击
      if (params.componentType === 'series' && params.name.length == 7) {
        // 模拟数据，后只需调用接口
        let option = this.state.option;
        option.series[0].itemStyle = {
          normal: {
            color: WeaEchart.colors[params.dataIndex],
          },
        };
        getReportData({ timeSag: '0', fromdate: `${params.name}-01`, enddate: `${params.name}-31` });
        year && this.setState({ option }, () => {
          setState({ year: false });
        });
      }
    });
  }

  resetOptionColor() {
    let { option } = this.state;
    option.series[0].itemStyle = {
      normal: {
        color: (params) => {
          if (params.name.length == 7) {
            return WeaEchart.colors[params.dataIndex % 10];
          }
            return WeaEchart.colors[0];
        },
      },
    };
  }

  downloadImg() {
    const echartid = this.refs.chart.chart.id;
		const cvs = jQuery(`div[_echarts_instance_='${echartid}'] canvas`)[0];
		ReportUtil.downloadCvs2Img(cvs);
  }

  render() {
    $(window).resize(() => {
      this.refs.chart && this.refs.chart.chart.resize();
    });
    let { option } = this.state;
    const { year, setState, getReportData, resetOptionColor, condition, lastParams } = this.props.smsReportStore;
    const xData = this.props.reportData.xAxis && this.props.reportData.xAxis.data || [];


    let isEmptyNow = isEmpty(option.xAxis.data) && isEmpty(option.series[0].data);
    if (resetOptionColor) {
       this.resetOptionColor();
       setState({ resetOptionColor: false });
    }
    let search_condition = toJS(condition);
    let time_condition = {};
    search_condition.forEach((item, i) => {
      if (item.domkey == 'timeSag') {
        time_condition = item;
      }
    });
    let backname = '';
    let backTimeTag = '';
    if (time_condition && time_condition.options) {
      time_condition.options.forEach((option, index) => {
          if (lastParams.timeSag == option.key) {
            backname = option.showname;
            backTimeTag = option.key;
          }
      });
    }
    xData.length > 15 ? option.xAxis.axisLabel.rotate = '45' : option.xAxis.axisLabel.rotate = '0';

    return (
          <div className="sms-report-echarts">
                  <div className="sms-report-echarts-title">
                      {getLabel(384210, '短信数量统计')}
                      {!isEmptyNow && <i className="icon-coms-download2" onClick={this.downloadImg.bind(this)} />}
                  </div>
              <div className="sms-report-echarts-sub">
                {
                  isEmptyNow ? (
                    <div className="sms-report-blank">
                      <i className="icon-coms-blank" />
                      <div className="count-charts-text">{getLabel(384202, '暂无报表')}</div>
                    </div>
                  ) : (
                    <WeaEchart ecId={`${this && this.props && this.props.ecId || ''}_WeaEchart@kp2pkh`} ref="chart" chartName={''} option={this.state.option} chartAction={this.chartAction} />
                  )
                }
                {!year && (
                    <div className="sms-report-echarts-sub-year">
                      <a onClick={() => {
                        option.series[0].itemStyle = {
                          normal: {
                            color: (params) => {
                              if (params.name.length == 7) {
                                return WeaEchart.colors[params.dataIndex % 10];
                              }
                                return WeaEchart.colors[0];
                            },
                          },
                        };
                        this.setState({ option }, () => {
                          setState({ year: true });
                          getReportData(lastParams);
                        });
                      }}
                      >{getLabel(1290, '返回') + backname}</a>
                    </div>
                  )
                }
              </div>
        </div>
    );
  }
}

export default SmsReportEcharts;
